package com.ygqh.baby.controller.admin;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.mp.api.NotifyApi;
import com.foxinmy.weixin4j.mp.message.NotifyMessage;
import com.foxinmy.weixin4j.tuple.News;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.MsgType;
import com.ygqh.baby.ao.QueryInfo;
import com.ygqh.baby.ao.ResultSet;
import com.ygqh.baby.po.WxCustomMsgDetail;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.service.WxCustomMsgDetailService;
import com.ygqh.baby.service.WxMpAuthorityService;
import com.ygqh.baby.service.YgUserService;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.ExceptionUtil;

@Controller
@RequestMapping("/admin/weixincustom")
public class WeixinCustomMessageController extends BaseController<Object, java.lang.Long> {

	@Autowired
	private WxCustomMsgDetailService wxCustomMsgDetailService;
	@Autowired
	private WxMpAuthorityService wxMpAuthorityService;
	@Autowired
	private YgUserService ygUserService;

	@RequestMapping("searchWeixinMessage")
	@ResponseBody
	public Map<String, Object> searchWeixinMessage(String title, QueryInfo queryInfo, Date startDate, Date endDate) {
		ResultSet<WxCustomMsgDetail> resultSet = wxCustomMsgDetailService.search(queryInfo, title, startDate, endDate);
		return resultSet.toDatatables(null);
	}

	@RequestMapping("saveWeixinMessage")
	@ResponseBody
	public Message saveWeixinMessage(String weixinMessage, HttpServletRequest request, HttpServletResponse response, String userName) throws WeixinException {
		List<WxCustomMsgDetail> wxCustomMsgDetails = JSON.parseObject(weixinMessage, new TypeReference<List<WxCustomMsgDetail>>() {
		});
		// 先删除当前日期的数据
		wxCustomMsgDetailService.updateStatus(wxCustomMsgDetails.get(0).getSendDate());
		for (WxCustomMsgDetail detail : wxCustomMsgDetails) {
			wxCustomMsgDetailService.saveOrUpdate(detail);
		}
		try {
			sendMessageTest(wxCustomMsgDetails, userName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS_MESSAGE;
	}

	/**
	 * 消息保存成功后，发送给指定用户查看
	 * @param wxCustomMsgDetails
	 * @param userName
	 */
	public void sendMessageTest(List<WxCustomMsgDetail> wxCustomMsgDetails, String userName) {
		if (CollectionUtils.isEmpty(wxCustomMsgDetails) || StringUtils.isBlank(userName)) {
			return;
		}
		YgUser ygUser = ygUserService.findByUserName(userName);
		News news = new News();
		for (WxCustomMsgDetail detail : wxCustomMsgDetails) {
			String msgLinkUrl = detail.getMsgLinkUrl();
			String sourceCode = DateConvertUtils.format(new Date(), "yyyyMMdd");
			if (msgLinkUrl.indexOf("?") != -1) {
				msgLinkUrl = msgLinkUrl + "&sourceCode=" + sourceCode;
			} else {
				msgLinkUrl = msgLinkUrl + "?sourceCode=" + sourceCode;
			}
			news.addArticle(detail.getMsgTitle(), null, detail.getMsgImagePath(), msgLinkUrl);
		}
		NotifyMessage notifyMessage = new NotifyMessage(ygUser.getOpenId(), news);
		NotifyApi notifyAPI = new NotifyApi(wxMpAuthorityService.findTokenHolder());
		try {
			notifyAPI.sendNotify(notifyMessage);
		} catch (Exception e) {
			e.printStackTrace();
			if (e.getMessage().indexOf("45015") == -1) {
				logger.error("发送微信客服消息失败openId:" + ygUser.getOpenId() + ", " + ExceptionUtil.getExceptionMsg(e));
			}
		}
	}

	@RequestMapping("findCustomMessageByDay")
	@ResponseBody
	public Message findCustomMessageById(@RequestParam Date day, MsgType msgType) {
		return Message.success(wxCustomMsgDetailService.findBySendDateAndType(day, msgType == null ? MsgType.News : msgType));
	}

	@RequestMapping("deleteCustomMessageByDay")
	@ResponseBody
	public Message deleteCustomMessageByDay(@RequestParam Date day, MsgType msgType) {
		wxCustomMsgDetailService.updateStatus(day);
		return Message.success(null);
	}

}
